//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class MergedCellsRecord : WorksheetLevelRecord
    {
        private readonly List<RangeAddress16> _items = new List<RangeAddress16>();

        public MergedCellsRecord(IEnumerable<Cell> cells)
        {
            Contract.Requires(cells != null);
            foreach (Cell cell in cells)
            {
                var range = new RangeAddress(cell.Address,
                                             cell.Address +
                                             new CellRelativeAddress(cell.RowSpan - 1,
                                                                     cell.ColumnSpan - 1));
                Items.Add((RangeAddress16) range);
            }
        }

        public MergedCellsRecord()
        {
        }

        public List<RangeAddress16> Items
        {
            get
            {
                Contract.Ensures(Contract.Result<List<RangeAddress16>>() != null);
                return _items;
            }
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.MergeCells; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            var count = (ushort) Items.Count;
            context.WriteUInt16(count);
            foreach (RangeAddress16 item in Items)
                item.Write(context.Writer);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            ushort count = context.ReadUInt16();
            for (int i = 0; i < count; i++)
                Items.Add(new RangeAddress16(context.Reader));
        }

        internal override void Apply(BiffReaderWorksheetContext context)
        {
            foreach (RangeAddress16 a in (this).Items)
            {
                context.Worksheet.Merge(Range.FromAddress(context.Worksheet, (RangeAddress) a));
#if DEBUG
                Cell test = context.Worksheet[((RangeAddress) a).TopLeft.Label];
#endif
            }
        }

        #region Nested type: CellRangeAddress

        public struct CellRangeAddress

        {
            public ushort firstColumn;
            public ushort firstRow;
            public ushort lastColumn;
            public ushort lastRow;
        }

        #endregion
    }
}